package client;

import java.util.List;

import client.bean.Member;
import client.bean.Plan;
import client.components.PlanView;
import client.persistance.Adminko;
import client.persistance.AdminkoAsync;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

public class TimeBookController {
	private static AdminkoAsync serv = Adminko.App.getInstance();
	private static PlanModel planModel = client.PlanModel.instance;

	private TimeBookController() {
	}

	public static void clearRootPabel() {
		RootPanel.get().clear();
	}

	public static void updatePlans() {
		AsyncCallback<List<Plan>> plansAsyncCallback = getPlansAsyncCallback();
		serv.getPlans(plansAsyncCallback);
	}

	private static AsyncCallback<List<Plan>> getPlansAsyncCallback() {
		return new AsyncCallback<List<Plan>>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("refillPlansTable failed");
			}

			@Override
			public void onSuccess(List<Plan> result) {
				planModel.setPlans(result);
			}
		};
	}

	public static void displayPlansPanel(Plan plan) {
		RootPanel.get().add(new PlanView(plan));
	}

	public static void informUsersByEmail(Plan plan) {
		serv.informMembers(plan, new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Members can't be informed nor. Please try again.");
			}

			@Override
			public void onSuccess(Void result) {
				Window.alert("Members will be informed by email.");
			}
		});
	}

	public static void addMember(final PlanView planView, final Plan plan, final Member member) {
		serv.addMember(member, new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Can't add member. Please try again later.");
			}

			@Override
			public void onSuccess(Void result) {
				planModel.addMember(plan, member);
				planView.repaint();
			}
		});
	}
}
